package itdep.security;

import itdep.domain.security.Account;
import itdep.services.security.AccountService;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Date;

/**
 * @author Ivan Khalopik
 * @version $Revision: 30 $ $Date: 2010-06-19 20:18:23 +0000 (Sat, 19 Jun 2010) $
 */
public class IisUserService implements UserDetailsService, ApplicationListener {
	private final AccountService accountService;

	public IisUserService(AccountService accountService) {
		this.accountService = accountService;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		final Account account = accountService.getByEmail(username);

		if (account != null) {
			return new IisUser(account);
		}

		throw new UsernameNotFoundException("UserBean \"" + username + "\" not found");
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof AuthenticationSuccessEvent) {
			final Authentication auth = ((AuthenticationSuccessEvent) event).getAuthentication();
			accountService.refreshAccessTime(auth.getName(), new Date(event.getTimestamp()));
		}
	}
}
